package cn.yuanqiao.web.controller.archive.appManager;

import cn.yuanqiao.archive.appManager.domain.TenantFields;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.domain.TenantRelevance;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.web.page.TableDataInfo;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 元数据明细Controller
 *
 * @author yuanqiao
 * @date 2023-06-09
 */
@RestController
@RequestMapping("/archive/cateMdataList")
public class TenantCateMdataListController extends BaseController
{
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;

    /**
     *
     * 档案门类查询元数据方案明细
     * @author syd
     * @param yqdaMdataList
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:list')")
    @GetMapping("/list")
    @Log(title = "档案门类元数据明细查询", businessType = BusinessType.SELECT)
    public TableDataInfo list(TenantMdataList yqdaMdataList)
    {
        List<TenantMdataList> list = tenantMdataListService.selectYqdaMdataListList(yqdaMdataList);
        return getDataTable(list);
    }

    /**
     * 导出元数据明细列表
     */
    //@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:export')")
    //@Log(title = "元数据明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TenantMdataList yqdaMdataList)
    {
        if(yqdaMdataList == null || yqdaMdataList.getGroupId() == null){
            throw new ServiceException("参数错误");
        }
        List<TenantMdataList> list = tenantMdataListService.selectYqdaMdataListList(yqdaMdataList);
        ExcelUtil<TenantMdataList> util = new ExcelUtil<TenantMdataList>(TenantMdataList.class);
        util.exportExcel(response, list, "元数据明细数据");
    }

    /**
     * 获取元数据明细详细信息
     */
    /*//@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(yqdaMdataListService.selectYqdaMdataListById(id));
    }
    */

    /**
     * 获取元数据明细详细信息
     */
    //@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:query')")
    @GetMapping(value = "/{id}")
    @Log(title = "档案门类获取元数据明细详细信息", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tenantMdataListService.selectYqdaMdataListById(id));
    }

    /**
     * 新增元数据明细
     */
    /*//@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:add')")
    @Log(title = "元数据明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HddaMDataList yqdaMdataList)
    {
        return toAjax(yqdaMdataListService.insertYqdaMdataList(yqdaMdataList));
    }*/

    /**
     * 档案门类元数据方案明细添加字段
     * @author syd
     * @param ids
     * @param categoryId
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:add')")
    @Log(title = "档案门类元数据方案明细添加字段", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestParam("ids") String ids,@RequestParam("categoryId") Long categoryId,@RequestParam("type") Integer type) throws SQLException {
        if(StringUtils.isEmpty(ids) || StringUtils.isNull(categoryId)){
            return AjaxResult.error("请检查出入参数");
        }else {
            return toAjax(tenantMdataListService.insertYqdaMdataList(ids,categoryId,type));
        }
    }

    /**
     * @author syd
     * 档案门类元数据方案明细修改
     * @param yqdaMdataList
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:edit')")
    @Log(title = "档案门类元数据方案明细修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TenantMdataList yqdaMdataList)
    {
        //if(StringUtils.isNull(yqdaMdataList.getId()) || StringUtils.isNull(yqdaMdataList.getGroupId())){
        //    return AjaxResult.error("请检查输入参数！");
        //}else {
        return toAjax(tenantMdataListService.updateYqdaMdataList(yqdaMdataList,yqdaMdataList.getIds()));
        //}
    }

    /**
     * 档案门类元数据方案明细删除
     * @author syd
     * @param ids
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('archive:YqdaMdataList:remove')")
    @Log(title = "档案门类元数据方案明细删除", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids,@RequestParam("categoryId") Long categoryId,@RequestParam("type") Integer type) throws SQLException {
        return toAjax(tenantMdataListService.deleteYqdaMdataListByIds(ids,categoryId,type));
    }

    /**
     *  档案门类元数据明细添加查询基础数据
     *  @author syd
     *  @RequestParam Long groupId, @RequestParam String type, @RequestParam String fieldCaption, @RequestParam String fieldName
     */
    @PostMapping("/listByGroupId")
    @Log(title = "档案门类元数据明细添加查询基础数据", businessType = BusinessType.SELECT)
    public TableDataInfo getGroupDataList(@RequestParam("groupId") Long groupId, @RequestParam("type") String type,
                                          @RequestParam("fieldCaption") String fieldCaption, @RequestParam("fieldName") String fieldName){
        if(StringUtils.isNull(groupId) || StringUtils.isEmpty(type)){
            throw new ServiceException("参数错误！");
        }
        startPage();
        TenantFields yqfields = new TenantFields();
        yqfields.setType(type);
        yqfields.setFieldCaption(fieldCaption);
        yqfields.setFieldName(fieldName);
        List<TenantFields> getGroupDataList = tenantMdataListService.getGroupDataList(yqfields,groupId);
        return getDataTable(getGroupDataList);
    }

    /**
     * 查询已勾选元数据项列表
     * @param groupId
     * @return
     */
    @GetMapping("/getHddaMDataListByIsMetadata")
    public AjaxResult getHddaMDataListByIsMetadata(@RequestParam Long groupId){
        if(StringUtils.isNull(groupId)){
            return AjaxResult.error("参数错误！");
        }
        TenantMdataList mDataList = new TenantMdataList();
        mDataList.setGroupId(groupId);
        mDataList.setIsMetadata(1);
        return AjaxResult.success(tenantMdataListService.selectYqdaMdataListList(mDataList));
    }

    /**
     * 复制元数据项验证验证复制到的元数据方案中是否有重复
     * @param groupId
     * @return
     */
    @GetMapping("/copyIsRepeat")
    public AjaxResult copyIsRepeat(@RequestParam String ids,@RequestParam Long groupId,@RequestParam Integer type){
        if(StringUtils.isEmpty(ids) || StringUtils.isNull(groupId) || StringUtils.isNull(type)){
            return AjaxResult.error("参数错误！");
        }
        String msg = tenantMdataListService.copyIsRepeat(ids,groupId,type);
        if(StringUtils.isEmpty(msg)){
            return AjaxResult.success("200");
        }else {
            return AjaxResult.success("重复项有："+msg+"，请选择覆盖或者跳过？");
        }
    }

    /**
     * 复制到
     * type = 1 覆盖原来明细 type = 2 跳过
     * @return
     */
    @PostMapping("/copyToGroup")
    public AjaxResult copyToGroup(@RequestParam String ids,@RequestParam Long groupId,@RequestParam String type){
        if(StringUtils.isEmpty(ids) || StringUtils.isNull(groupId)){
            return AjaxResult.error("参数错误！");
        }
        tenantMdataListService.copyToGroup(ids,groupId,StringUtils.isNotEmpty(type) ? Integer.valueOf(type):null);
        return AjaxResult.success();
    }

    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,Long groupId,Integer type) throws Exception
    {
        if(file.isEmpty() || StringUtils.isNull(groupId) || StringUtils.isNull(type)){
            return AjaxResult.error("参数错误！");
        }
        ExcelUtil<TenantMdataList> util = new ExcelUtil<>(TenantMdataList.class);
        List<TenantMdataList> dataLists = util.importExcel(file.getInputStream());
        tenantMdataListService.importHddaMDataList(dataLists,groupId,type);
        return AjaxResult.success();
    }
    /**
     * 获取展示字段
     * @Param type 0:件 1:卷 3:项目
     * @Param categoryId 门类id
     * @Param level jian juan xiangmu efile 必填
     * @Param menuId 菜单id
     *
     * 使用1
     *      "level": "jian",   查询的层级
     *     "type": 0            门类的层级
     *     返回为所有type=0的门类的jian层展示字段
     * 使用2
     *     "level": "jian",
     *     "categoryId": 194342526180790272,
     *     "menuId":1068
     *     返回为菜单id为1068,门类194342526180790272的jian层展示字段
     *
     * @return List<Map<>>  FIELD_NAME,FIELD_CAPTION,SHOWTYPE
     */
    @PostMapping("/getshowfield")
    public AjaxResult getshowfield(@RequestBody JSONObject json)
    {
        List<Map<String,String>> list=tenantMdataListService.getshowfield(json);
        return success(list);
    }

    /**
     * 获取查询字段
     * @param json
     * json中  categoryId 门类id
     *          menuId    菜单id
     *          type      哪一层  0,1,2,3
     * @return list<Map<>> FIELD_CAPTION,FIELD_NAME,SHOWTYPE,IS_QUERY,FIELDTYPE
     */
    @PostMapping("/getqueryfield")
    public AjaxResult getqueryfield(@RequestBody JSONObject json)
    {
        List<Map<String,String>> list=tenantMdataListService.getqueryfield(json.getLong("categoryId"),json.getLong("menuId"),json.getInteger("type"));
        return success(list);
    }

    /**
     * 获取查询字段
     * @param json
     * json中  categoryId 门类id
     *          menuId    菜单id
     *          type      哪一层  0,1,2,3
     * @return list<Map<>>  FIELD_CAPTION,FIELD_NAME,EXPORT_COLUMN_NAME,EXPORT_ORDER_NO
     */
    @GetMapping("/getexportfield")
    public AjaxResult getexportfield(@RequestBody JSONObject json)
    {
        List<Map<String,String>> list=tenantMdataListService.getqueryfield(json.getLong("categoryId"),json.getLong("menuId"),json.getInteger("type"));
        return success(list);
    }
    /**
     * 获取新增字段
     * @param json
     * json中  categoryId 门类id
     *          menuId    菜单id
     *          type      哪一层  0,1,2,3
     * @return list<Map<>>  FIELD_CAPTION,FIELD_NAME,SHOWTYPE,DEFAULT_VALUE,DATA_LENGTH,IS_NO_EMPTY
     */
    @PostMapping("/getaddfield")
    public AjaxResult getaddfield(@RequestBody JSONObject json)
    {
        Map<String, Object> getaddfield = tenantMdataListService.getaddfield(json.getLong("categoryId"), json.getLong("menuId"), json.getInteger("type"));
        return success(getaddfield);
    }
    /**
     * 获取修改字段
     * @param json
     * json中  categoryId 门类id
     *          menuId    菜单id
     *          type      哪一层  0,1,2,3
     * @return list<Map<>>  FIELD_CAPTION,FIELD_NAME,SHOWTYPE,DEFAULT_VALUE,DATA_LENGTH,IS_NO_EMPTY
     */
    @PostMapping("/getupdatefield")
    public AjaxResult getupdatefield(@RequestBody JSONObject json)
    {
        Map<String, Object> getupdatefield = tenantMdataListService.getupdatefield(json.getLong("categoryId"), json.getLong("menuId"), json.getInteger("type"));
        return success(getupdatefield);
    }

    /**
     * 获取排序
     * @param json
     * json中  categoryId 门类id
     *          menuId    菜单id
     *          type      哪一层 0,1,2,3
     * @return String bgqx desc,mj asc
     */
    @PostMapping("/getorder")
    public AjaxResult getorder(@RequestBody JSONObject json)
    {
        String orderstr=tenantMdataListService.getorder(json.getLong("categoryId"),json.getLong("menuId"),json.getInteger("type"));
        return success(orderstr);
    }

    /**
     * 获取件档号存储字段
     * @param
     * @throws IOException
     */
    @GetMapping("/getFileNumberField")
    public AjaxResult getFileNumberField(@RequestParam("categoryId") Long categoryId)
    {
        List<TenantMdataList> list = tenantMdataListService.getFileNumberField(categoryId);
        return success(list);
    }
    @Log(title = "获取关联列表",businessType = BusinessType.SELECT)
    /** 获取关联列表 */
    @PostMapping("/getrelevancelist")
    public TableDataInfo getrelevancelist(@RequestBody JSONObject json)
    {
        List<TenantRelevance> list=tenantMdataListService.getrelevancelist(json);
        return getDataTable(list);
    }
    /** 获取关联字段
     * 只获取下一层,项目->卷/卷->件
     * @params field 当前字段
     * @params nowlevel  当前层级
     * @params relelevel  关联字段的层级
     * @params fieldtype  当前字段类型
     * @params groupId 当前的元数据方案id
     * */
    @Log(title = "获取关联字段",businessType = BusinessType.SELECT)
    @PostMapping("/getrelevancefield")
    public AjaxResult getrelevancefield(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = tenantMdataListService.getrelevancefield(json);
        return success(list);
    }

    /** 添加关联
     * @params field 当前字段
     * @params relefield 关联字段
     * @params nowlevel  当前层级
     * @params relelevel  关联字段的层级
     * @params fieldtype  当前字段类型
     * @params relefieldtype  关联字段类型
     * @params relation 关联
     * @params groupId 当前的元数据方案id
     * */
    @Log(title = "添加关联",businessType = BusinessType.INSERT)
    @PostMapping("/addrelevance")
    public AjaxResult addrelevance(@RequestBody JSONObject json)
    {
        int i = tenantMdataListService.addrelevance(json);
        return success(i);
    }

    @Log(title = "获取关联明细",businessType = BusinessType.INSERT)
    @PostMapping("/getreledetail/{id}")
    public AjaxResult getreledetail(@PathVariable("id")Long id)
    {
        TenantRelevance relevance = tenantMdataListService.getreledetail(id);
        return success(relevance);
    }
    @Log(title = "修改关联",businessType = BusinessType.UPDATE)
    @PostMapping("/editrele")
    public AjaxResult editrele(@RequestBody TenantRelevance relevance)
    {
        int i = tenantMdataListService.editrele(relevance);
        return success(i);
    }
    @Log(title = "删除关联",businessType = BusinessType.DELETE)
    @PostMapping("/delterele")
    public AjaxResult delterele(@RequestBody JSONObject json)
    {
        int i = tenantMdataListService.delterele(json);
        return success(i);
    }


    @Log(title = "著录修改时获取关联",businessType = BusinessType.DELETE)
    @PostMapping("/getrelevanceforadd")
    public AjaxResult getrelevanceforadd(@RequestBody JSONObject json)
    {
        List<Map<String,Object>> list = tenantMdataListService.getrelevanceforadd(json);
        return success(list);
    }
    @Log(title = "档案门类元数据方案明细批量修改", businessType = BusinessType.UPDATE)
    @PutMapping("/batch")
    public AjaxResult batchEdit(@RequestBody TenantMdataList yqdaMdataList)
    {
        //if(StringUtils.isNull(yqdaMdataList.getId()) || StringUtils.isNull(yqdaMdataList.getGroupId())){
        //    return AjaxResult.error("请检查输入参数！");
        //}else {
        return toAjax(tenantMdataListService.batchUpdateYqdaMdataList(yqdaMdataList,yqdaMdataList.getIds()));
        //}
    }
    //手动输入,上移下移弃用(空值,重复值的影响,无法使用
    /*@Log(title = "下移元数据排序",businessType = BusinessType.UPDATE)
    @PostMapping("/moveDown")
    public AjaxResult moveDown(@RequestBody JSONObject json)
    {
        return success(tenantMdataListService.moveDown(json.getLong("metadataListIds"),json.getLong("groupId"),json.getLong("categoryId"),json.getInteger("type")));

    }
    @Log(title = "上移元数据排序",businessType = BusinessType.UPDATE)
    @PostMapping("/moveUp")
    public AjaxResult moveUp(@RequestBody JSONObject json)
    {
        return success(tenantMdataListService.moveUp(json.getLong("metadataListIds"),json.getLong("groupId"),json.getLong("categoryId"),json.getInteger("type")));

    }*/

}
